__author__ = 'ipetrov'

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.expected_conditions import *

import unittest

class any_window_other_than(object):
    def __init__(self, existing_windows):
        self.existing_windows = existing_windows

    def __call__(self, driver):
        handles = driver.window_handles
        diff = set(handles)-set(self.existing_windows)
        return iter(diff).next() if len(diff) > 0 else False


class Untitled(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://localhost/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def open_and_login(self):
        driver = self.driver
        try:
            driver.get(self.base_url + "/php4dvd/")
            driver.find_element_by_id("username").clear()
            driver.find_element_by_id("username").send_keys("admin")
            driver.find_element_by_name("password").clear()
            driver.find_element_by_name("password").send_keys("admin")
            driver.find_element_by_name("submit").click()
            WebDriverWait(driver, 30).until(presence_of_element_located((By.ID, "q")))
        except:
            raise Exception("Login failed.")

    def add_new_movie(self, title, year, saw_movie_early=True):
        driver = self.driver
        driver.find_element_by_css_selector("img[alt=\"Add movie\"]").click()
        self.add_title(title)
        driver.find_element_by_name("aka").clear()
        driver.find_element_by_name("aka").send_keys("qwerty1")
        self.add_year(year)
        driver.find_element_by_name("duration").clear()
        driver.find_element_by_name("duration").send_keys("120")
        driver.find_element_by_name("rating").clear()
        driver.find_element_by_name("rating").send_keys("5")
        driver.find_element_by_id("own_no").click()
        self.set_saw_movie_early(saw_movie_early)
        driver.find_element_by_id("loaned_yes").click()
        driver.find_element_by_name("loanname").clear()
        driver.find_element_by_name("loanname").send_keys("David Cameron")
        self.add_trailer_url(title)
        driver.find_element_by_name("notes").clear()
        driver.find_element_by_name("notes").send_keys("my notes")
        driver.find_element_by_name("taglines").clear()
        driver.find_element_by_name("taglines").send_keys("my taglines")
        driver.find_element_by_name("plotoutline").clear()
        driver.find_element_by_name("plotoutline").send_keys("my plot outline")
        driver.find_element_by_name("plots").clear()
        driver.find_element_by_name("plots").send_keys("my plots")
        driver.find_element_by_id("text_languages_0").clear()
        driver.find_element_by_id("text_languages_0").send_keys("my lang")
        driver.find_element_by_name("subtitles").clear()
        driver.find_element_by_name("subtitles").send_keys("no sub")
        driver.find_element_by_name("audio").clear()
        driver.find_element_by_name("audio").send_keys("5x1")
        driver.find_element_by_name("video").clear()
        driver.find_element_by_name("video").send_keys("720p")
        driver.find_element_by_name("country").clear()
        driver.find_element_by_name("country").send_keys("USA")
        driver.find_element_by_name("genres").clear()
        driver.find_element_by_name("genres").send_keys("drama")
        driver.find_element_by_name("director").clear()
        driver.find_element_by_name("director").send_keys("director")
        driver.find_element_by_name("writer").clear()
        driver.find_element_by_name("writer").send_keys("writer")
        driver.find_element_by_name("producer").clear()
        driver.find_element_by_name("producer").send_keys("producer")
        driver.find_element_by_name("music").clear()
        driver.find_element_by_name("music").send_keys("music")
        driver.find_element_by_name("cast").clear()
        driver.find_element_by_name("cast").send_keys("cast")
        driver.find_element_by_id("submit").click()
        try:
            WebDriverWait(driver, 30).until(lambda driver: driver.find_element_by_class_name("maininfo_full")
                                            .find_element_by_xpath("./h2"))
        except:
            raise Exception("Error occurred during adding new movie")

    def add_title(self, title):
        driver = self.driver
        try:
            driver.find_element_by_name("name").clear()
            driver.find_element_by_name("name").send_keys(str(title))
            WebDriverWait(driver, 10).until(invisibility_of_element_located((By.CLASS_NAME, "error")))
        except:
            raise Exception("Title is required field")

    def add_year(self,year):
        driver = self.driver
        driver.find_element_by_name("year").clear()
        driver.find_element_by_name("year").send_keys(str(year))
        try:
            WebDriverWait(driver, 2).until(lambda driver: driver.find_element_by_id('updateform').find_element_by_xpath(
                "./table/tbody/tr[4]/td[2]/label").is_displayed())
        except:
            pass
        else:
            text=driver.find_element_by_id('updateform').find_element_by_xpath(
                "./table/tbody/tr[4]/td[2]/label").text
            if text == 'Please enter a valid number':
                raise Exception("Invalid year")
            elif text == 'This field is required':
                raise Exception("Year is required field")

    def set_saw_movie_early(self,state):
        driver = self.driver
        if self._get_saw_movie_early() != state:
            if state == True:
                driver.find_element_by_id("seen_yes").click()
            else:
                driver.find_element_by_id("seen_no").click()

    def _get_saw_movie_early(self):
        driver = self.driver
        if driver.find_element_by_id("seen_yes").is_selected():
            return True
        else:
            return False

    def add_trailer_url(self, title):
        driver = self.driver
        try:
            original_window = driver.current_window_handle
            existing_windows = driver.window_handles
            driver.find_element_by_css_selector("img[alt=\"Search for movie trailer\"]").click()
            new_window = WebDriverWait(driver, 20).until(any_window_other_than(existing_windows))
            driver.switch_to_window(new_window)
            driver.find_element_by_id("masthead-search-term").send_keys(' ' + title)
            driver.find_element_by_id("search-btn").send_keys(Keys.RETURN)
            driver.find_element_by_id('search-results').find_element_by_xpath("./li[2]/div[2]/h3/a").get_attribute("href")
            url = driver.find_element_by_id('search-results').find_element_by_xpath("./li[2]/div[2]/h3/a").get_attribute("href")
            driver.close()
            driver.switch_to_window(original_window)
            driver.find_element_by_name("trailer").clear()
            driver.find_element_by_name("trailer").send_keys(url)
        except:
            raise Exception("Error occurred during adding trailer url")

    def check_data(self,title, year):
        driver = self.driver
        if driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./h2").text != str(title + ' (' + str(year) + ')'):
            raise Exception("Wrong title or year")
        try:
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Loaned out to David Cameron')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'drama')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'DVD, 120 minutes')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Rating: 5')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Languages: my lang')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Subtitles: no sub')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Country: USA')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Director: director')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Writer: writer')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Producer: producer')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Music: music')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Video: 720p')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Audio: 5x1')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div[contains(text(),'Personal notes my notes')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div/div[contains(text(),'my plot outline')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div/div/div/ul/li[contains(text(),'cast')]")
            driver.find_element_by_class_name("maininfo_full").find_element_by_xpath("./div/ol/li[contains(text(),'my plots')]")
        except:
            raise Exception("Wrong data")

    def test_untitled(self):
        self.open_and_login()
        self.add_new_movie(' ',1987,'Yes')
        self.check_data('Titanic',1987)

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException, e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException, e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

